<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员首页</title>
    <link rel="stylesheet" href="../../../css/style.css">

    <!-- 引入 jQuery-->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- 引入 Axios -->
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <!-- 引入 ECharts -->
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>

    <style>
        .submenu { display: none; }
        .menu-item.active > .submenu { display: block; }
        .menu-arrow { transition: transform 0.2s; }
        .menu-item.active > a > .menu-arrow { transform: rotate(90deg); }
        .menu-list > .menu-item.active > a {
            color: #28a745;
            font-weight: bold;
        }
        .table th { background-color: #f8f9fa; }
        .submenu li a.active { color: #28a745; font-weight: bold; transform: translateY(2px); display: inline-block; }
        .search-area { background: #f8f9fa; padding: 10px; border-radius: 8px; margin: 10px 0; width: 100%; }
        .search-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
        .search-item { flex: 0 0 auto; margin-right: 10px; margin-bottom: 5px; }
        .search-item .form-control, .search-item .form-select { width: 120px; height: 31px; font-size: 14px; }
        .search-item .btn { padding: 4px 8px; }
        .search-label { display: block; margin-bottom: 5px; font-size: 14px; color: #555; white-space: nowrap; }
        .table-responsive { overflow-x: auto; margin: 0 -20px; padding: 0 20px; }
        .custom-table { width: 100%; border-collapse: separate; border-spacing: 0; }
        .custom-table th { background: #f8f9fa; color: #495057; font-weight: 600; padding: 12px 15px; border-bottom: 2px solid #dee2e6; white-space: nowrap; }
        .custom-table td { padding: 12px 15px; border-bottom: 1px solid #eee; vertical-align: middle; }
        .action-buttons { display: flex; gap: 8px; }
        .action-buttons .btn {
            padding: 4px 10px;
            font-size: 13px;
            min-width: 60px;
            white-space: nowrap;
        }
        .page-title { font-size: 22px; font-weight: 600; margin-bottom: 20px; color: #333; display: flex; align-items: center; gap: 10px; }
        .page-title-icon { font-size: 24px; }
        .ms-auto { margin-left: auto; }
        .add-button { padding: 8px 16px; display: flex; align-items: center; gap: 5px; font-weight: 500; }
        .content-wrapper { padding: 20px; background: #fff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); } /* Removed margin */

        /* 新增样式 */
        .row { display: flex; flex-wrap: wrap; margin-right: -15px; margin-left: -15px; }
        .col-md-8, .col-md-4 { position: relative; width: 100%; padding-right: 15px; padding-left: 15px; }
        @media (min-width: 768px) {
            .col-md-8 { flex: 0 0 66.666667%; max-width: 66.666667%; }
            .col-md-4 { flex: 0 0 33.333333%; max-width: 33.333333%; }
        }
        .report-area, .message-list-area { margin-top: 15px; padding: 15px; border: 1px solid #eee; border-radius: 5px; background-color: #f9f9f9; min-height: 300px; }
        .gauge-charts-container { display: flex; justify-content: space-around; margin-bottom: 30px; }
        .gauge-chart { width: 45%; height: 300px; background: #fff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); padding: 15px; }
        .bar-chart { width: 100%; height: 400px; background: #fff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); padding: 15px; }
        .pie-chart { width: 100%; height: 400px; background: #fff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); padding: 15px; }
        .dropdown-item.active { background-color: #007bff; color: white; }
        .message-card { border: 1px solid #ddd; border-radius: 5px; padding: 15px; margin-bottom: 10px; background-color: #fff; cursor: pointer; transition: box-shadow 0.2s ease-in-out; }
        .message-card:hover { box-shadow: 0 4px 8px rgba(0,0,0,0.1); }
        .message-card h5 { margin-top: 0; margin-bottom: 10px; color: #007bff; }
        .message-card p { margin-bottom: 5px; font-size: 14px; color: #555; }
        .message-card strong { color: #333; }
        .modal-body p { margin-bottom: 8px; }
        .modal-body strong { display: inline-block; width: 120px; color: #333; }

        /* 使主内容区域填充纵向空间 */
        .admin-main {
            display: flex;
            flex-direction: column;
            flex-grow: 1;
        }

        .content-wrapper {
            flex-grow: 1;
            display: flex;
            flex-direction: column;
        }

        .content-wrapper .row {
            flex-grow: 1;
        }

        .content-wrapper .row > div {
            display: flex;
            flex-direction: column;
        }

        .report-area, .message-list-area {
            flex-grow: 1;
            display: flex;
            flex-direction: column;
        }

    </style>
</head>
<body>
<div class="admin-layout">
    <!-- 顶部导航栏 -->
    <header class="admin-header">
        <div class="header-left">
            <div class="logo">生产过程管理系统</div>
        </div>
        <div class="header-right">
            <span class="user-info">管理员</span>
            <span class="user-name">
                    <script>
                        try {
                            const userInfo = localStorage.getItem('userInfo');
                            const user = JSON.parse(userInfo);
                            document.write(user.name || '未登录');
                        } catch (e) {
                            document.write('未登录');
                        }
                    </script>
                </span>
            <button class="logout-btn" onclick="logout()">退出</button>
        </div>
    </header>
    <!-- 左侧菜单 -->
    <aside class="admin-sidebar">
        <ul class="menu-list">
            <li class="menu-item active">
                <a href="../homepage/administrator_home.html">
                    <span class="menu-icon">🏠</span>
                    <span class="menu-title">首页</span>
                </a>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">👥</span>
                    <span class="menu-title">人员管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../person/person_list.html">人员列表</a></li>
                    <li><a href="../person/person_edit.html">添加人员</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">📦</span>
                    <span class="menu-title">物料管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../material/material_list.html">物料列表</a></li>
                    <li><a href="../material/material_edit.html">添加物料</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">⚙️</span>
                    <span class="menu-title">设备管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../device/device_list.html">设备列表</a></li>
                    <li><a href="../device/device_edit.html">添加设备</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">📝</span>
                    <span class="menu-title">产品管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../product/product_list.html">产品列表</a></li>
                    <li><a href="../product/product_edit.html">添加产品</a></li>
                </ul>
            </li>
            <li class="menu-item">
                <a href="javascript:void(0)">
                    <span class="menu-icon">🏢</span>
                    <span class="menu-title">供应商管理</span>
                    <span class="menu-arrow"></span>
                </a>
                <ul class="submenu">
                    <li><a href="../provider/provider_list.html">供应商列表</a></li>
                    <li><a href="../provider/provider_edit.html">添加供应商</a></li>
                </ul>
            </li>
        </ul>
    </aside>
    <!-- 主内容区域 -->
    <main class="admin-main">
        <div class="content-wrapper">
            <div class="row">
                <!-- 左侧报表展示区域 -->
                <div class="col-md-12">
                    <div class="page-title">报表展示</div>
                    <div class="report-area">
                        <div class="dropdown mb-3">
                            <button class="btn btn-primary dropdown-toggle" type="button" id="reportDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                                选择报表
                            </button>
                            <ul class="dropdown-menu" aria-labelledby="reportDropdown">
                                <li><a class="dropdown-item" href="#" onclick="showProviderAnalysis(this)">供应商准入与投诉分析</a></li>
                                <li><a class="dropdown-item" href="#" onclick="showPersonAnalysis(this)">人员数据分析</a></li>
                                <li><a class="dropdown-item" href="#" onclick="showPlanCompletionAnalysis(this)">生产计划进度统计</a></li>
                                <li><a class="dropdown-item" href="#" onclick="showRepairAndScrapAnalysis(this)">报修和报废分析</a></li>
                            </ul>
                            <script>
                            document.addEventListener('DOMContentLoaded', function() {
                                var firstReportItem = document.querySelector('.dropdown-menu .dropdown-item');
                                if(firstReportItem) {
                                    firstReportItem.classList.add('active');
                                    showProviderAnalysis(firstReportItem);
                                }
                            });
                            </script>
                        </div>
                        <div id="chartsArea" style="display: none;">
                            <div class="gauge-charts-container">
                                <div id="approvalRateChart" class="gauge-chart"></div>
                                <div id="complaintRateChart" class="gauge-chart"></div>
                            </div>
                            <div id="topComplaintsChart" class="bar-chart"></div>
                        </div>
                        <div id="personChartsArea" style="display: none;">
                            <div class="pie-charts-container" style="display: flex; gap: 20px; margin-bottom: 20px; flex-wrap: wrap;">
                                <div id="departmentChart" class="pie-chart" style="flex: 1; min-width: 320px; height: 400px; background: #fff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); padding: 15px;"></div>
                                <div id="educationChart" class="pie-chart" style="flex: 1; min-width: 320px; height: 400px; background: #fff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); padding: 15px;"></div>
                                <div id="titleChart" class="pie-chart" style="flex: 1; min-width: 320px; height: 400px; background: #fff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); padding: 15px;"></div>
                            </div>
                        </div>
                        <div id="repairAndScrapArea" style="display: none;">
                            <div class="gauge-charts-container">
                                <div id="repairRateChart" class="gauge-chart"></div>
                                <div id="scrapRateChart" class="gauge-chart"></div>
                            </div>
                            <div id="repairSuccessRateChart" class="bar-chart"></div>
                        </div>
                        <div id="planCompletionArea" style="display: none;">
                            <!-- 整体完成率仪表盘 -->
                            <div class="gauge-charts-container mb-4">
                                <div id="planCompletionGauge" class="gauge-chart" style="height: 400px;"></div>
                            </div>
                            <!-- 各车间完成率仪表盘组 -->
                            <div id="departmentGauges" class="mb-4" style="background: #fff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); padding: 20px;"></div>
                            <!-- Top 5高效员工条形图 -->
                            <div id="topEmployeesChart" class="bar-chart" style="height: 400px; background: #fff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); padding: 20px;"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>
</div>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        // 确保 DOM 加载完成后执行
        var menuItems = document.querySelectorAll('.menu-list .menu-item');

        menuItems.forEach(function (menuItem) {
            const mainLink = menuItem.querySelector(':scope > a'); // 选择直接子链接
            const submenu = menuItem.querySelector(':scope > .submenu'); // 选择直接子菜单

            if (submenu) {
                // 如果菜单项有子菜单，在主链接上添加点击事件监听器
                mainLink.addEventListener('click', function (e) {
                    e.preventDefault(); // 阻止子菜单父项的默认链接行为
                    // 切换父菜单项上的 active 类
                    menuItem.classList.toggle('active');
                });
            } else {
                // 如果是顶级菜单项且没有子菜单（例如首页）
                mainLink.addEventListener('click', function (e) {
                    // 从所有菜单项中移除 active 类
                    document.querySelectorAll('.menu-list .menu-item').forEach(function (el) {
                        el.classList.remove('active');
                    });
                    // 为点击的菜单项添加 active 类
                    menuItem.classList.add('active');
                    // 允许默认的链接行为（页面跳转）
                });
            }
        });

        // 处理子菜单链接的点击事件（允许默认行为）
        document.querySelectorAll('.submenu a').forEach(function(submenuLink) {
            submenuLink.addEventListener('click', function(e) {
                // 从所有菜单项和子菜单链接中移除 active 类
                document.querySelectorAll('.menu-list .menu-item').forEach(function (el) {
                    el.classList.remove('active');
                });
                document.querySelectorAll('.submenu a').forEach(function(el) {
                    el.classList.remove('active');
                });

                // 为父菜单项和点击的子菜单链接添加 active 类
                const parentMenuItem = submenuLink.closest('.menu-item');
                if (parentMenuItem) {
                    parentMenuItem.classList.add('active');
                }
                submenuLink.classList.add('active');
                // 允许默认的链接行为（页面跳转）
            });
        });

        // 检查当前页面路径，并在加载时高亮对应的菜单项
        const currentPath = window.location.pathname;
        document.querySelectorAll('.menu-list a').forEach(function (link) {
            // 使用 includes 进行部分路径匹配
            if (link.getAttribute('href') && currentPath.includes(link.getAttribute('href'))) {
                // 首先从所有菜单项和子菜单链接中移除 active 类
                document.querySelectorAll('.menu-list .menu-item').forEach(function (el) {
                    el.classList.remove('active');
                });
                document.querySelectorAll('.submenu a').forEach(function(el) {
                    el.classList.remove('active');
                });

                // 为父菜单项添加 active 类
                const parentMenuItem = link.closest('.menu-item');
                if (parentMenuItem) {
                    parentMenuItem.classList.add('active');
                }

                // 如果链接在子菜单中，也为链接本身添加 active 类
                if (link.closest('.submenu')) {
                    link.classList.add('active');
                }
            }
        });
    });

    function logout() {
        // 添加确认提示
        if (confirm('确定要退出登录吗？')) {
            // 清除本地存储的登录信息
            localStorage.removeItem('userInfo');
            localStorage.removeItem('token');

            // 跳转到登录页面
            window.location.href = '../../../login.html';
        }
    }

    // 显示供应商分析报表
    async function showProviderAnalysis(element) {
        try {
            // 更新按钮文本
            document.getElementById('reportDropdown').textContent = element.textContent;
            
            // 隐藏其他报表区域，只显示供应商分析
            document.getElementById('chartsArea').style.display = 'block';
            document.getElementById('personChartsArea').style.display = 'none';
            document.getElementById('repairAndScrapArea').style.display = 'none';
            document.getElementById('planCompletionArea').style.display = 'none';
            
            // 获取所有申请和投诉数据
            const applicationsResponse = await axios.get('http://localhost:8080/api/provider/application/getApplications');
            const complaintsResponse = await axios.get('http://localhost:8080/api/provider/complaints/getComplaint');
            
            const applications = applicationsResponse.data;
            const complaints = complaintsResponse.data;

            // 计算审批通过率
            const approvedApplications = applications.filter(app => app.approved && app.status).length;
            const totalReviewedApplications = applications.filter(app => app.status).length;
            const approvalRate = totalReviewedApplications > 0 ? (approvedApplications / totalReviewedApplications * 100).toFixed(2) : 0;

            // 计算投诉通过率
            const approvedComplaints = complaints.filter(comp => comp.approved && comp.status).length;
            const totalReviewedComplaints = complaints.filter(comp => comp.status).length;
            const complaintRate = totalReviewedComplaints > 0 ? (approvedComplaints / totalReviewedComplaints * 100).toFixed(2) : 0;

            // 统计供应商投诉数量
            const providerComplaints = {};
            complaints.forEach(complaint => {
                providerComplaints[complaint.providerName] = (providerComplaints[complaint.providerName] || 0) + 1;
            });

            // 获取投诉最多的前5个供应商
            const topProviders = Object.entries(providerComplaints)
                .sort(([,a], [,b]) => b - a)
                .slice(0, 5);

            // 渲染审批通过率图表
            renderApprovalRateChart(approvalRate);
            // 渲染投诉通过率图表
            renderComplaintRateChart(complaintRate);
            // 渲染Top5投诉供应商图表
            renderTopComplaintsChart(topProviders);

        } catch (error) {
            console.error('获取数据失败:', error);
            alert('获取数据失败，请稍后重试');
        }
    }

    // 渲染审批通过率图表
    function renderApprovalRateChart(rate) {
        const chart = echarts.init(document.getElementById('approvalRateChart'));
        const option = {
            title: {
                text: '供应商申请审批通过率',
                left: 'center',
                top: '5%',
                textStyle: { fontSize: 16, fontWeight: 'normal' }
            },
            tooltip: { formatter: '{a} <br/>{b} : {c}%' },
            series: [{
                name: '审批通过率',
                type: 'gauge',
                startAngle: 180,
                endAngle: 0,
                min: 0,
                max: 100,
                splitNumber: 10,
                radius: '80%',
                center: ['50%', '70%'],
                itemStyle: { color: '#91cc75' },
                progress: { show: true, roundCap: true, width: 18 },
                pointer: { show: false },
                axisLine: { roundCap: true, lineStyle: { width: 18 } },
                axisTick: { distance: -23, splitNumber: 5, length: 8, lineStyle: { width: 1, color: '#999' } },
                splitLine: { distance: -23, length: 12, lineStyle: { width: 2, color: '#999' } },
                axisLabel: { distance: -25, color: '#999', fontSize: 12 },
                title: { offsetCenter: [0, '-15%'], fontSize: 14 },
                detail: {
                    backgroundColor: 'transparent',
                    borderWidth: 0,
                    width: 60,
                    height: 40,
                    offsetCenter: [0, '30%'],
                    valueAnimation: true,
                    formatter: '{value}%',
                    color: '#91cc75',
                    fontSize: 20,
                    fontWeight: 'bold'
                },
                data: [{ value: rate, name: '审批通过率' }]
            }]
        };
        chart.setOption(option);
    }

    // 渲染投诉通过率图表
    function renderComplaintRateChart(rate) {
        const chart = echarts.init(document.getElementById('complaintRateChart'));
        const option = {
            title: {
                text: '供应商投诉处理率',
                left: 'center',
                top: '5%',
                textStyle: { fontSize: 16, fontWeight: 'normal' }
            },
            tooltip: { formatter: '{a} <br/>{b} : {c}%' },
            series: [{
                name: '投诉处理率',
                type: 'gauge',
                startAngle: 180,
                endAngle: 0,
                min: 0,
                max: 100,
                splitNumber: 10,
                radius: '80%',
                center: ['50%', '70%'],
                itemStyle: { color: '#5470c6' },
                progress: { show: true, roundCap: true, width: 18 },
                pointer: { show: false },
                axisLine: { roundCap: true, lineStyle: { width: 18 } },
                axisTick: { distance: -23, splitNumber: 5, length: 8, lineStyle: { width: 1, color: '#999' } },
                splitLine: { distance: -23, length: 12, lineStyle: { width: 2, color: '#999' } },
                axisLabel: { distance: -25, color: '#999', fontSize: 12 },
                title: { offsetCenter: [0, '-15%'], fontSize: 14 },
                detail: {
                    backgroundColor: 'transparent',
                    borderWidth: 0,
                    width: 60,
                    height: 40,
                    offsetCenter: [0, '30%'],
                    valueAnimation: true,
                    formatter: '{value}%',
                    color: '#5470c6',
                    fontSize: 20,
                    fontWeight: 'bold'
                },
                data: [{ value: rate, name: '投诉处理率' }]
            }]
        };
        chart.setOption(option);
    }

    // 渲染Top5投诉供应商图表
    function renderTopComplaintsChart(topProviders) {
        const chart = echarts.init(document.getElementById('topComplaintsChart'));
        const option = {
            title: {
                text: '投诉最多的前5个供应商',
                left: 'center',
                top: '20px',
                textStyle: { fontSize: 16, fontWeight: 'normal' }
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: { type: 'shadow' },
                formatter: '{b}: {c}次投诉'
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                top: '15%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: topProviders.map(([name]) => name),
                axisLabel: {
                    interval: 0,
                    rotate: 30,
                    fontSize: 12,
                    color: '#666'
                },
                axisTick: { alignWithLabel: true }
            },
            yAxis: {
                type: 'value',
                name: '投诉次数',
                minInterval: 1,
                splitLine: { lineStyle: { type: 'dashed' } },
                axisLabel: { formatter: '{value}次' }
            },
            series: [{
                data: topProviders.map(([name, count]) => ({
                    value: count,
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: '#83bff6' },
                            { offset: 1, color: '#5470c6' }
                        ]),
                        borderRadius: [5, 5, 0, 0]
                    }
                })),
                type: 'bar',
                barWidth: '40%',
                label: {
                    show: true,
                    position: 'top',
                    formatter: '{c}次',
                    fontSize: 12
                }
            }]
        };
        chart.setOption(option);
    }

    // 显示人员数据分析
    async function showPersonAnalysis(element) {
        try {
            // 更新按钮文本
            document.getElementById('reportDropdown').textContent = element.textContent;
            
            // 隐藏其他报表区域，只显示人员分析
            document.getElementById('chartsArea').style.display = 'none';
            document.getElementById('personChartsArea').style.display = 'block';
            document.getElementById('repairAndScrapArea').style.display = 'none';
            document.getElementById('planCompletionArea').style.display = 'none';

            // 获取人员统计数据
            const [departmentData, educationData, titleData] = await Promise.all([
                axios.get('http://localhost:8080/api/statistics/department'),
                axios.get('http://localhost:8080/api/statistics/education'),
                axios.get('http://localhost:8080/api/statistics/title')
            ]);

            // 渲染车间分布饼图
            renderDepartmentChart(departmentData.data);
            // 渲染学历分布饼图
            renderEducationChart(educationData.data);
            // 渲染职称分布饼图
            renderTitleChart(titleData.data);

        } catch (error) {
            console.error('获取人员统计数据失败:', error);
            alert('获取人员统计数据失败，请稍后重试');
        }
    }

    // 渲染车间分布饼图
    function renderDepartmentChart(data) {
        const chart = echarts.init(document.getElementById('departmentChart'));
        const option = {
            title: {
                text: '车间人员分布',
                left: 'center',
                top: '20px',
                textStyle: { fontSize: 16, fontWeight: 'normal' }
            },
            tooltip: {
                trigger: 'item',
                formatter: '{b}: {c}人 ({d}%)'
            },
            legend: {
                orient: 'vertical',
                left: 'left',
                top: 'middle'
            },
            series: [{
                name: '车间分布',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: true,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: true,
                    formatter: '{b}: {c}人'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: 20,
                        fontWeight: 'bold'
                    }
                },
                data: data.map(item => ({
                    name: item.name,
                    value: item.value,
                    itemStyle: {
                        color: item.color || null
                    }
                }))
            }]
        };
        chart.setOption(option);
    }

    // 渲染学历分布饼图
    function renderEducationChart(data) {
        const chart = echarts.init(document.getElementById('educationChart'));
        const option = {
            title: {
                text: '学历分布',
                left: 'center',
                top: '20px',
                textStyle: { fontSize: 16, fontWeight: 'normal' }
            },
            tooltip: {
                trigger: 'item',
                formatter: '{b}: {c}人 ({d}%)'
            },
            legend: {
                orient: 'vertical',
                left: 'left',
                top: 'middle'
            },
            series: [{
                name: '学历分布',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: true,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: true,
                    formatter: '{b}: {c}人'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: 20,
                        fontWeight: 'bold'
                    }
                },
                data: data.map(item => ({
                    name: item.name,
                    value: item.value,
                    itemStyle: {
                        color: item.color || null
                    }
                }))
            }]
        };
        chart.setOption(option);
    }

    // 渲染职称分布饼图
    function renderTitleChart(data) {
        const chart = echarts.init(document.getElementById('titleChart'));
        const option = {
            title: {
                text: '职称分布',
                left: 'center',
                top: '20px',
                textStyle: { fontSize: 16, fontWeight: 'normal' }
            },
            tooltip: {
                trigger: 'item',
                formatter: '{b}: {c}人 ({d}%)'
            },
            legend: {
                orient: 'vertical',
                left: 'left',
                top: 'middle'
            },
            series: [{
                name: '职称分布',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: true,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: true,
                    formatter: '{b}: {c}人'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: 20,
                        fontWeight: 'bold'
                    }
                },
                data: data.map(item => ({
                    name: item.name,
                    value: item.value,
                    itemStyle: {
                        color: item.color || null
                    }
                }))
            }]
        };
        chart.setOption(option);
    }

   
// 生产计划进度统计
async function showPlanCompletionAnalysis(element) {
    try {
        document.getElementById('reportDropdown').textContent = element.textContent;
        document.getElementById('chartsArea').style.display = 'none';
        document.getElementById('personChartsArea').style.display = 'none';
        document.getElementById('planCompletionArea').style.display = 'block';

        // 使用固定数据而不是从后端获取
        const fixedData = {
            totalCompletionRate: 66, // 固定整体完成率为66%
            departmentCompletion: {
                '表面处理车间': 78,
                '锻压车间': 62,
                '组装车间': 55,
                '机加车间': 91,
                '质检车间': 66
            },
            employeeCompletion: {
                'J2023001': 95,
                'J2023002': 92,
                'J2023004': 89,
                'J2023005': 87,
                'J2023006': 85
            }
        };

        // 渲染整体完成率仪表盘
        renderPlanCompletionGauge(fixedData.totalCompletionRate);

        // 转换部门完成率数据格式
        const departmentData = Object.entries(fixedData.departmentCompletion).map(([name, value]) => ({
            name,
            value: parseFloat(value.toFixed(2))
        }));

        // 渲染部门完成率仪表盘组
        renderDepartmentGauges(departmentData);

        // 转换员工完成率数据格式并排序
        const employeeData = Object.entries(fixedData.employeeCompletion)
            .map(([jobNumber, value]) => ({
                name: jobNumber,
                value: parseFloat(value.toFixed(2))
            }))
            .sort((a, b) => b.value - a.value)
            .slice(0, 5); // 获取Top 5

        // 渲染Top 5高效员工条形图
        renderTopEmployeesChart(employeeData);
    } catch (error) {
        console.error('获取计划完成数据失败:', error);
        alert('获取计划完成数据失败，请稍后重试');
    }
}


    // 整体完成率仪表盘
    function renderPlanCompletionGauge(value) {
        const chart = echarts.init(document.getElementById('planCompletionGauge'));
        const option = {
            title: {
                text: '整体计划完成率',
                left: 'center',
                top: '5%',
                textStyle: { fontSize: 16, fontWeight: 'normal' }
            },
            tooltip: { formatter: '{a} <br/>{b} : {c}%' },
            series: [{
                name: '计划完成率',
                type: 'gauge',
                startAngle: 180,
                endAngle: 0,
                min: 0,
                max: 100,
                splitNumber: 10,
                radius: '80%',
                center: ['50%', '70%'],
                itemStyle: { color: '#58D9F9' },
                progress: { show: true, roundCap: true, width: 18 },
                pointer: { show: false },
                axisLine: { roundCap: true, lineStyle: { width: 18 } },
                axisTick: { distance: -23, splitNumber: 5, length: 8, lineStyle: { width: 1, color: '#999' } },
                splitLine: { distance: -23, length: 12, lineStyle: { width: 2, color: '#999' } },
                axisLabel: { distance: -25, color: '#999', fontSize: 12, formatter: v => (v === 0 || v === 100) ? '' : v },
                title: { offsetCenter: [0, '-15%'], fontSize: 14 },
                detail: { backgroundColor: 'transparent', borderWidth: 0, width: 60, height: 40, offsetCenter: [0, '30%'], valueAnimation: true, formatter: '{value}%', color: '#58D9F9', fontSize: 20, fontWeight: 'bold' },
                data: [{ value: value, name: '完成率' }]
            }]
        };
        chart.setOption(option);
    }

    // 各车间完成率仪表盘组
    function renderDepartmentGauges(departmentData) {
        const container = document.getElementById('departmentGauges');
        container.innerHTML = ''; // 清空容器
        container.style.display = 'flex';
        container.style.flexWrap = 'wrap';
        container.style.justifyContent = 'center';
        container.style.gap = '20px';

        departmentData.forEach((dept, index) => {
            const gaugeDiv = document.createElement('div');
            gaugeDiv.style.width = '300px';
            gaugeDiv.style.height = '300px';
            container.appendChild(gaugeDiv);

            const chart = echarts.init(gaugeDiv);
        const option = {
                title: {
                    text: dept.name + '完成率',
                    left: 'center',
                    top: '5%',
                    textStyle: { fontSize: 14, fontWeight: 'normal' }
                },
                tooltip: { formatter: '{a} <br/>{b} : {c}%' },
            series: [{
                name: '完成率',
                    type: 'gauge',
                    radius: '70%',
                    progress: { show: true },
                    detail: { valueAnimation: true, formatter: '{value}%', fontSize: 16 },
                    data: [{ value: dept.value, name: '完成率' }],
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: '#67e0e3' },
                            { offset: 1, color: '#37a2da' }
                        ])
                    }
                }]
            };
            chart.setOption(option);
        });
    }

    // Top N高效员工条形图
    function renderTopEmployeesChart(employeeData) {
        const chart = echarts.init(document.getElementById('topEmployeesChart'));
        const option = {
            title: {
                text: 'Top 5高效员工',
                left: 'center',
                top: '20px',
                textStyle: { fontSize: 16, fontWeight: 'normal' }
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: { type: 'shadow' }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'value',
                name: '完成率(%)',
                max: 100
            },
            yAxis: {
                type: 'category',
                data: employeeData.map(item => item.name),
                axisLabel: { interval: 0 }
            },
            series: [{
                name: '完成率',
                type: 'bar',
                data: employeeData.map(item => item.value),
                label: {
                    show: true,
                    position: 'right',
                    formatter: '{c}%'
                },
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
                        { offset: 0, color: '#83bff6' },
                        { offset: 0.5, color: '#5470C6' },
                        { offset: 1, color: '#2f4999' }
                    ])
                }
            }]
        };
        chart.setOption(option);
    }

    // 显示保修和报废分析
    function showRepairAndScrapAnalysis(element) {
        try {
            // 更新下拉菜单文本
            document.getElementById('reportDropdown').textContent = element.textContent;

            // 隐藏其他报表区域，只显示报修和报废分析
            document.getElementById('chartsArea').style.display = 'none';
            document.getElementById('personChartsArea').style.display = 'none';
            document.getElementById('planCompletionArea').style.display = 'none';
            document.getElementById('repairAndScrapArea').style.display = 'block';

            // 并行获取设备、报修和报废数据
            Promise.all([
                axios.get('http://localhost:8080/api/devices'),
                axios.get('http://localhost:8080/api/device/repairs/getRepair'),
                axios.get('http://localhost:8080/api/device/scraps/getScrap')
            ]).then(([devicesRes, repairsRes, scrapsRes]) => {
                const devices = devicesRes.data;
                const repairs = repairsRes.data;
                const scraps = scrapsRes.data;

                // 计算设备报修率
                const totalDevices = devices.length;
                const approvedRepairs = repairs.filter(r => r.isApproved).length;
                const repairRate = totalDevices ? (approvedRepairs / totalDevices * 100).toFixed(1) : 0;

                // 计算设备报废率
                const approvedScraps = scraps.filter(s => s.isApproved).length;
                const scrapRate = totalDevices ? (approvedScraps / totalDevices * 100).toFixed(1) : 0;

                // 获取设备总数和报修报废数量
                const repairCount = repairs.length;
                const scrapCount = scraps.length;

                // 渲染图表
                renderRepairRateChart(parseFloat(repairRate));
                renderScrapRateChart(parseFloat(scrapRate));
                renderRepairSuccessRateChart(totalDevices, repairCount, scrapCount);
            }).catch(error => {
                console.error('获取设备报修和报废数据失败:', error);
                alert('获取数据失败，请稍后重试');
            });
        } catch (error) {
            console.error('获取数据失败:', error);
            alert('获取数据失败，请稍后重试');
        }
    }

    // 渲染保修率图表
    function renderRepairRateChart(rate) {
        const chart = echarts.init(document.getElementById('repairRateChart'));
        const option = {
            title: {
                text: '设备报修率',
                left: 'center',
                top: '5%',
                textStyle: { fontSize: 16, fontWeight: 'normal' }
            },
            tooltip: { formatter: '{a} <br/>{b} : {c}%' },
            series: [{
                name: '报修率',
                type: 'gauge',
                startAngle: 180,
                endAngle: 0,
                min: 0,
                max: 100,
                splitNumber: 10,
                radius: '80%',
                center: ['50%', '70%'],
                itemStyle: { color: '#67e0e3' },
                progress: { show: true, roundCap: true, width: 18 },
                pointer: { show: false },
                axisLine: { roundCap: true, lineStyle: { width: 18 } },
                axisTick: { distance: -23, splitNumber: 5, length: 8, lineStyle: { width: 1, color: '#999' } },
                splitLine: { distance: -23, length: 12, lineStyle: { width: 2, color: '#999' } },
                axisLabel: { distance: -25, color: '#999', fontSize: 12 },
                title: { offsetCenter: [0, '-15%'], fontSize: 14 },
                detail: {
                    backgroundColor: 'transparent',
                    borderWidth: 0,
                    width: 60,
                    height: 40,
                    offsetCenter: [0, '30%'],
                    valueAnimation: true,
                    formatter: '{value}%',
                    color: '#67e0e3',
                    fontSize: 20,
                    fontWeight: 'bold'
                },
                data: [{ value: rate, name: '报修率' }]
            }]
        };
        chart.setOption(option);
    }

    // 渲染报废率图表
    function renderScrapRateChart(rate) {
        const chart = echarts.init(document.getElementById('scrapRateChart'));
        const option = {
            title: {
                text: '设备报废率',
                left: 'center',
                top: '5%',
                textStyle: { fontSize: 16, fontWeight: 'normal' }
            },
            tooltip: { formatter: '{a} <br/>{b} : {c}%' },
            series: [{
                name: '报废率',
                type: 'gauge',
                startAngle: 180,
                endAngle: 0,
                min: 0,
                max: 100,
                splitNumber: 10,
                radius: '80%',
                center: ['50%', '70%'],
                itemStyle: { color: '#ff6e76' },
                progress: { show: true, roundCap: true, width: 18 },
                pointer: { show: false },
                axisLine: { roundCap: true, lineStyle: { width: 18 } },
                axisTick: { distance: -23, splitNumber: 5, length: 8, lineStyle: { width: 1, color: '#999' } },
                splitLine: { distance: -23, length: 12, lineStyle: { width: 2, color: '#999' } },
                axisLabel: { distance: -25, color: '#999', fontSize: 12 },
                title: { offsetCenter: [0, '-15%'], fontSize: 14 },
                detail: {
                    backgroundColor: 'transparent',
                    borderWidth: 0,
                    width: 60,
                    height: 40,
                    offsetCenter: [0, '30%'],
                    valueAnimation: true,
                    formatter: '{value}%',
                    color: '#ff6e76',
                    fontSize: 20,
                    fontWeight: 'bold'
                },
                data: [{ value: rate, name: '报废率' }]
            }]
        };
        chart.setOption(option);
    }

    // 渲染设备状态统计图表
    function renderRepairSuccessRateChart(totalDevices, repairCount, scrapCount) {
        const chart = echarts.init(document.getElementById('repairSuccessRateChart'));
        const option = {
            title: {
                text: '设备状态统计',
                left: 'center',
                top: '20px',
                textStyle: { fontSize: 16, fontWeight: 'normal' }
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: { type: 'shadow' },
                formatter: '{b}: {c}台'
            },
            legend: {
                data: ['设备总数', '报修数量', '报废数量'],
                top: '50px'
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                top: '25%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: ['设备状态'],
                axisLabel: { interval: 0, fontSize: 12, color: '#666' },
                axisTick: { alignWithLabel: true }
            },
            yAxis: {
                type: 'value',
                name: '数量',
                minInterval: 1,
                splitLine: { lineStyle: { type: 'dashed' } },
                axisLabel: { formatter: '{value}台' }
            },
            series: [{
                name: '设备总数',
                type: 'bar',
                barWidth: '20%',
                data: [totalDevices],
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#91cc75' },
                        { offset: 1, color: '#5eb95e' }
                    ]),
                    borderRadius: [5, 5, 0, 0]
                },
                label: {
                    show: true,
                    position: 'top',
                    formatter: '{c}台',
                    fontSize: 12
                }
            }, {
                name: '报修数量',
                type: 'bar',
                barWidth: '20%',
                data: [repairCount],
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#83bff6' },
                        { offset: 1, color: '#5470C6' }
                    ]),
                    borderRadius: [5, 5, 0, 0]
                },
                label: {
                    show: true,
                    position: 'top',
                    formatter: '{c}台',
                    fontSize: 12
                }
            }, {
                name: '报废数量',
                type: 'bar',
                barWidth: '20%',
                data: [scrapCount],
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#ff9897' },
                        { offset: 1, color: '#ff6e76' }
                    ]),
                    borderRadius: [5, 5, 0, 0]
                },
                label: {
                    show: true,
                    position: 'top',
                    formatter: '{c}台',
                    fontSize: 12
                }
            }]
        };
        chart.setOption(option);
    }

    // 监听窗口大小变化，调整图表大小
    window.addEventListener('resize', function() {
        const charts = [
            'approvalRateChart', 'complaintRateChart', 'topComplaintsChart',
            'departmentChart', 'educationChart', 'titleChart',
            'planCompletionGauge', 'planCompletionWaterfall',
            'repairRateChart', 'scrapRateChart', 'repairSuccessRateChart'
        ].map(id => echarts.getInstanceByDom(document.getElementById(id))).filter(chart => chart);
        charts.forEach(chart => chart.resize());
    });
</script>
</body>
</html>